<template>
  <div>
    <el-dialog
      title="添加角色"
      :visible="dialogVisible"
      width="500px"
      @close="close"
    >
      <el-form
        ref="formData"
        label-width="120px"
        :model="formData"
        :rules="rules"
      >

        <el-form-item
          label="角色名称"
          prop="name"
        >
          <el-input
            v-model="formData.name"
            style="width: 300px;"
            size="mini"
          />
        </el-form-item>

        <el-form-item label="启用" prop="state">
          <el-switch
            v-model="formData.state"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>

        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="formData.description"
            style="width: 300px;"
            size="mini"
            type="textarea"
            :rows="3"
          />
        </el-form-item>

        <el-row type="flex" justify="center">
          <el-col :span="12">
            <el-button size="mini" type="primary" @click="btnOk">添加</el-button>
            <el-button size="mini" @click="close">取消</el-button>
          </el-col>
        </el-row>

      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { addRole } from '@/api/role'
export default {
  name: 'RoleDialog',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        name: '',
        description: '',
        state: 0
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async btnOk() {
      try {
        await this.$refs.formData.validate()
        await addRole(this.formData)
        // 通知父组件更新列表
        this.$emit('updateRoleList')
        this.$message.success('新增角色成功')
        this.close()
      } catch (error) {
        console.dir(error)
      }
    },
    close() {
      // 重置表单
      this.$refs.formData.resetFields()
      this.$emit('update:dialog-visible', false)
    }
  }
}
</script>

<style>

</style>
